package com.sinosoft.gateway.web;

import com.sinosoft.gateway.notice.NoticeQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.Valid;
import java.io.IOException;

@Controller
public class SseController {


    @Autowired
    NoticeQueue noticeQueue;

    @RequestMapping(path = "/stream", method = RequestMethod.GET)
    public SseEmitter stream() throws IOException {

        SseEmitter emitter = new SseEmitter();
        noticeQueue.addEmitter(emitter);
        emitter.onCompletion(() -> noticeQueue.removeEmitter(emitter));
        return emitter;
    }

//    @ResponseBody
//    @RequestMapping(path = "/chat", method = RequestMethod.POST)
//    public Message sendMessage(@Valid Message message) {
//
//        log.info("Got message" + message);
//
//        emitters.forEach((SseEmitter emitter) -> {
//            try {
//                emitter.send(message, MediaType.APPLICATION_JSON);
//            } catch (IOException e) {
//                emitter.complete();
//                emitters.remove(emitter);
//                e.printStackTrace();
//            }
//        });
//        return message;
//    }

}
